import React from "react";
import BaseScreen from "../BaseScreen";
import { upload } from '../../service/TaskService'
import { getTOKEN } from '../../utils/StorageUtil'
// import { HintDialog } from '../../view/Dialog'
// 图片上传
class Upload extends BaseScreen {
  constructor(props) {
    super(props);
    this.imgurls = []
    this.state = {
      imgurl: '',
      alertMsg: "",
      style: this.props.style,
    }
  }
  // 获取文件
  getFile = (e) => {
    var file = e.target.files[0]
    if (file.size > 1024 * 1024 * 5) {
      this.showMsgDialog('图片太大无法上传，请选择小于5M的图片');
      return
    }
    // for(var i = 0; i < files.length; i++){  
      this.uploadImg({
        token: getTOKEN(),
        file: file
      })
    // }
    // base64
    // var reader = new FileReader()
    // reader.onload = function (e) {
    //   const result = this.result;    //data:base64
    //   that.props.getImgUrl(result)
    //   that.setState({
    //     style:{}
    //   })
    // };
    // reader.readAsDataURL(file);
  }
  getImgUrl = (e, func) => {
    const imgurl = e
    const image = new Image()
    // 获取图片宽高
    image.onload = function (e) {
      let width = this.width
      let height = this.height

      func(
        {
          imgurl: imgurl,
          width: width,
          height: height
        })

    }
    image.src = e
  }

  uploadImg = (params) => {
    this.props.setLoading({ loading: true });
    upload(params)
      .then(
        res => {
          if (res.error_code === 0) {
            this.getImgUrl(res.data.saved_files[0], this.props.setImgs)
            // this.showMsgDialog('上传成功');
            // alert('上传成功')
          }
          if (res.error_code === 20) {
            this.showMsgDialog('未发现有上传文件或文件过大');
          }
          if (res.error_code === 22) {
            this.showMsgDialog('服务器保存文件错误');
          }
          this.props.setLoading({ loading: false });

        }
      ).catch(
        err => {
          console.log(err)
          this.props.setLoading({ loading: false });
        }
      )
  }

  render() {
    const { style } = this.props
    // let userPlatform = ''
    // if(navigator.userAgent.indexOf("iPhone")>0){
    //   userPlatform = 'iPhone'
    // }else if(navigator.userAgent.indexOf("Android")>0){
    //   userPlatform = 'Android'
    // }else{
    //   userPlatform = ''
    // }
    // alert(userPlatform)

    return (
      <div >
        {this.renderMsgDialog()}
        {/* {userPlatform === 'iPhone'&& <input style={style} ref={this.props.inputRef} type='file' onChange={this.getFile} value={this.state.imgurl} />} */}
        {/* {userPlatform === 'Android'&& <input style={style} ref={this.props.inputRef} type='file' onChange={this.getFile} value={this.state.imgurl} />} */}
        <input style={style} ref={this.props.inputRef} type='file' onChange={this.getFile} value={this.state.imgurl} />
      </div>
    )
  }
};


const inputStyle = { border: 'none', outline: 'none' }
export default Upload